import os

PROJECT_NAME = 'pixiv_down'
PROJECT_VERSION = '2024.12.0'

# Set up configuration
CONFIG_FILENAME = 'scons.cfg'
opts = Variables(CONFIG_FILENAME)
opts.AddVariables(
    PathVariable('prefix',
        help='Installation prefix',
        default='/usr/local',
        validator=PathVariable.PathIsDir
    ),
    PathVariable('eprefix',
        help='Installation prefix for executable files',
        default='${prefix}',
        validator=PathVariable.PathIsDir
    ),
    PathVariable('bindir',
        help='Executable directory',
        default='${eprefix}/bin',
        validator=PathVariable.PathIsDir
    ),
    PathVariable('datarootdir',
        help='The root of the directory tree for read-only architecture-independent data files.',
        default='${prefix}/share',
        validator=PathVariable.PathIsDir
    ),
    PathVariable('datadir',
        help='The directory for installing read-only architecture-independent data files.',
        default='${datarootdir}',
        validator=PathVariable.PathIsDir
    ),
    PathVariable('includedir',
        help='The directory for installing header files to be included by other user programs.',
        default='${prefix}/include',
        validator=PathVariable.PathIsDir
    ),
    PathVariable('libdir',
        help='Shared object code libraries',
        default='${eprefix}/lib',
        validator=PathVariable.PathIsDir
    ),
    PathVariable('mandir',
        help='The top-level directory for installing the man pages.',
        default='${datarootdir}/man',
        validator=PathVariable.PathIsDir
    ),
    BoolVariable('with_gm_converter',
        help='(Linux) Compile the GraphicsMagick converter plugin.',
        default='yes'
    )
)

# Make sure scons will use the correct D compiler (from DC)
tools = ['dmd', 'cc', 'link']

if 'DC' in os.environ:
    tools[0] = os.environ['DC'].lower()
    tools[0] = 'ldc' if tools[0] == 'ldc2' else tools[0]

if 'CC' in os.environ:
    tools[1] = os.environ['CC'].lower()

env = Environment(
    tools=tools,
    options=opts,
    PROJECT_NAME=PROJECT_NAME,
    PROJECT_VERSION=PROJECT_VERSION,
)

scons_version = (0, 0, 0)
try:
    # GetSConsVersion is defined in 4.8.0
    scons_version = GetSConsVersion()
except NameError:
    pass

# SCons versions older than 4.6.0 don't correctly set GDC's version flag.
if scons_version[0] < 4 or (scons_version[0] == 4 and scons_version[1] < 6):
    if env['DC'] == 'gdc':
        env['DVERPREFIX'] = '-fversion='

# SCons doesn't set the correct version flag for ldc.
if env['DC'] == 'ldc2' or env['DC'] == 'ldc':
    env['DVERPREFIX'] = '--d-version='

# GDC has a linking issue in at least version 12.
if env['DC'] == 'gdc':
    # TODO: Only apply to version 12
    print('*** GDC detected. Using -fall-instantiations. (WILL SLOW COMPILATION) ***')
    env.Append(DFLAGS=['-fall-instantiations'])


opts.Save(CONFIG_FILENAME, env)
Help(opts.GenerateHelpText(env))

# Create pd_version.d
def vcs_tag(self, *, command, fallback=env['PROJECT_VERSION'], input_file, output_file, replace_string='@VCS_TAG@'):
    import subprocess

    tag = fallback
    process = subprocess.run(command, capture_output=True)
    if process.returncode == 0:
        tag = process.stdout.decode('utf-8').strip()

    with open(input_file) as infile, open(output_file, 'w+') as outfile:
        content = infile.read()
        replaced = content.replace(replace_string, tag)
        outfile.write(replaced)

    return output_file

env.AddMethod(vcs_tag)

# Easier sharing of paths from SConscript to parent SConscript
def files(self, *args):
    return list(map(lambda p: os.path.join(os.getcwd(), p), args))

env.AddMethod(files, 'Files')


# Build pixiv_down

SConscript([
    'docs/SConscript',
    'source/SConscript',
], exports='env')

# Install

install_data = env.Alias('install-data', env['datarootdir'])
install_exec = env.Alias('install-exec', env['eprefix'])
env.Alias('install', [install_exec, install_data])
